﻿#region Librerias

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using ESF.General.Entity;
using ESF.DMS.Entities.Load;
using ESF.MSExcel;
using System.IO;
using ESF.General;

#endregion


namespace ESF.DMS.DataAccess.Load
{
	public static class AdoLoadFolderChanges
	{
		public static void Verify_SaludTotal_Red_Changes (int pMonitoredDirectoryID, out List<IEnterprise> pEnterprises, out List<SaludTotal_Red_Changes> pChanges)
		{
			DirectoryInfo loadFolder;
			DirectoryInfo loadFolderMonDir;

			string excelFile;

			DataTable dtbEnterprises;

			DataTable dtbChanges;


			loadFolder = ReadConfig.GetAppSettingFolder ("ImageCatalogsUploadDirectory");

			loadFolderMonDir = loadFolder.GetDirectories ().Where (d => d.Name.StartsWith (pMonitoredDirectoryID.ToString())).FirstOrDefault ();
			
			if (loadFolderMonDir == null || !loadFolderMonDir.Exists)
			{
				throw new GenericInfoException (string.Format ("Directory for Monitored {0} was not found", pMonitoredDirectoryID));
			}

			excelFile = Path.Combine (loadFolderMonDir.FullName, "ListaExcel", "ListaExcel.xlsx");

			
			#region Enterprises
			
			dtbEnterprises = ESF.MSExcel.XlsReaderOleDb.GetAllCells (excelFile, "IPSs", true);

			pEnterprises = new List<IEnterprise> (dtbEnterprises.Rows.Count);

			foreach (DataRow rowEnt in dtbEnterprises.Rows)
			{
				pEnterprises.Add (
					new BaseEnterprise ()
					{
						IdentificationType = new BasicReference ()
						{
							Code = "NIT"
						},
						IdentificationNumber = rowEnt ["NIT"].ToString (),
						Name = rowEnt ["Nombre"].ToString ()
					});
			}

			#endregion


			#region Changes

			SaludTotal_Red_Changes currentChange;


			dtbChanges = ESF.MSExcel.XlsReaderOleDb.GetAllCells (excelFile, "Cambios", true);

			pChanges = new List<SaludTotal_Red_Changes> (dtbChanges.Rows.Count);

			foreach (DataRow rowChange in dtbChanges.Rows)
			{
				currentChange = new SaludTotal_Red_Changes ()
				{
					NIT = rowChange ["NIT"].ToString (),
					Sucursal = rowChange ["Sucursal"].ToString (),
					CarpetaVigente = rowChange ["Carpeta Vigente"].ToString (),
					CarpetaHistorico = rowChange["Carpeta Historico"].ToString(),
					FechaVigencia = TextHelper.GetNullableDateTime (rowChange["Fecha Vigencia (yyyy-MM-dd)"].ToString (), "yyyy-MM-dd", "yyyy/MM/dd"),
					NumeroHojas = TextHelper.GetInt (rowChange["Num Hojas"].ToString()),
					TipoActualizacion = rowChange ["Tipo Actualizacion"].ToString ()
				};

				pChanges.Add (currentChange);
			}

			// TODO: Verificar cargue loadFolderMonDir

			#endregion
		}
	}
}
